package com.tao.picture.ui.person.activity

import android.Manifest
import android.content.Intent
import android.text.TextUtils
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import com.tao.BasicActivity
import com.tao.net.ServiceGenerator
import com.tao.picture.base.data.PreferenceStore
import com.tao.picture.databinding.ActivitySplashBinding
import com.tao.picture.databinding.DialogUrlBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import javax.inject.Inject

@AndroidEntryPoint
class SplashActivity : BasicActivity<ActivitySplashBinding>() {

    @Inject
    lateinit var generator: ServiceGenerator

    @Inject
    lateinit var store: PreferenceStore

    override val binding: ActivitySplashBinding by lazy {
        ActivitySplashBinding.inflate(layoutInflater)
    }

    override fun initData() {
        super.initData()
        // 请求权限
        requestNeedPermissions()
    }

    @AfterPermissionGranted(ALL_PERMISSION)
    private fun requestNeedPermissions() {
        if (EasyPermissions.hasPermissions(this, *PERMISSION_ARRAY)) {
            lifecycleScope.launch {
                var url = store.readBaseUrl()
                if (TextUtils.isEmpty(url)) {
                    // 手动输入服务地址
                    val binding = DialogUrlBinding.inflate(layoutInflater)
                    AlertDialog.Builder(this@SplashActivity)
                        .setTitle("提示")
                        .setView(binding.root)
                        .setPositiveButton("确定") { dialog, which ->
                            url = binding.et.text.toString()
                            lifecycleScope.launch {
                                store.saveBaseUrl(url)
                            }
                            generator.refresh(url)
                            startActivity(Intent(this@SplashActivity, PersonActivity::class.java))
                            finish()
                        }.show()
                } else {
                    generator.refresh(url)
                    startActivity(Intent(this@SplashActivity, PersonActivity::class.java))
                    finish()
                }
            }

        } else {
            EasyPermissions.requestPermissions(
                this, "请允许权限",
                ALL_PERMISSION, *PERMISSION_ARRAY
            )
        }
    }

    companion object {
        private val PERMISSION_ARRAY = arrayOf(
            // 内存读写权限
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
        private const val ALL_PERMISSION = 0x0001
    }
}